from api.extension.filter import SelfFilterBackend
from api.extension.mixins import DigListModelMixin, DigCreateModelMixin, DigUpdateModelMixin, DigDestroyModelMixin
from api.models import Topic
from api.serializers.topic import TopicSerializer
from django_filters import FilterSet, NumberFilter
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework.viewsets import GenericViewSet


class TopicFilterSet(FilterSet):
    latest_id = NumberFilter(field_name='id', lookup_expr='lt')

    class Meta:
        model = Topic
        fields = ['latest_id']


class TopicView(DigListModelMixin, DigCreateModelMixin, DigUpdateModelMixin, DigDestroyModelMixin, GenericViewSet):
    """ 话题 """
    # 筛选当前登录用户提交的数据，latest_id之后的数据
    filter_backends = [SelfFilterBackend, DjangoFilterBackend]
    filterset_class = TopicFilterSet

    queryset = Topic.objects.filter(deleted=False).order_by('-id')
    serializer_class = TopicSerializer

    def perform_create(self, serializer):
        serializer.save(user=self.request.user)

    def perform_destroy(self, instance):
        instance.deleted = True
        instance.save()
